package com.example.concurrentprogramming8016.lockInterruptibly;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyanhao
 * @Date 2023-02-08 14:40
 */
public class LockInterruptiblyDemo {
    private Lock lock = new ReentrantLock();

    public void doBussiness() {
        String name = Thread.currentThread().getName();
        try {
            System.out.println(name + "开始获取锁");
            lock.lockInterruptibly();
            System.out.println(name + " 得到锁");
            System.out.println(name + " 开始干活");
            for (int i = 0; i < 5; i++) {
                Thread.sleep(1000);
                System.out.println(name + " : " + i);
            }
        } catch (InterruptedException e) {
            System.out.println(name + " 被中断了");
            System.out.println(name + " 做些别的事情");
        } finally {
            try {
                lock.unlock();
                System.out.println(name + " 释放锁");
            } catch (Exception e) {
                System.out.println(name + " 没有得到锁的线程运行结束");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockInterruptiblyDemo lockInterruptiblyDemo = new LockInterruptiblyDemo();

        Thread t1 = new Thread(() -> {
            lockInterruptiblyDemo.doBussiness();
        }, "t1");
        Thread t2 = new Thread(() -> {
            lockInterruptiblyDemo.doBussiness();
        }, "t2");
        t1.start();
        TimeUnit.SECONDS.sleep(10);
        t2.start();
        TimeUnit.SECONDS.sleep(10);
        //线程t1没有得到锁 中断t1的等待
        t1.interrupt();

    }

}
